-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathzad2.py
56 lines (38 loc) · 999 Bytes
/
zad2.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
"""
ZŁOŻONOŚĆ:
Obliczeniowa: O(n)
Pamięciowa: O(n)
"""
from zad2testy import runtests
def store_sums(T):
root = T
def dfs(curr, parent):
total = 0
for i, node in enumerate(curr.edges):
if node is parent:
continue
total += dfs(node, curr) + curr.weights[i]
curr.w_sum = total
return total
dfs(root, None)
def balance(T):
store_sums(T)
root = T
total_sum = T.w_sum
best_diff = float('inf')
best_edge = None
def dfs(curr, parent):
nonlocal best_edge, best_diff
for i, node in enumerate(curr.edges):
if node is parent:
continue
a = node.w_sum
b = total_sum - a - curr.weights[i]
diff = abs(a - b)
if diff < best_diff:
best_diff = diff
best_edge = curr.ids[i]
dfs(node, curr)
dfs(root, None)
return best_edge
runtests(balance)